package com.crrcdt.websocket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;

/**
 * @author lj on 2020/11/17.
 * @version 1.0
 */
public class UdpSendClient implements Runnable{
    //1、建立一个socket
    DatagramSocket socket =null;
    //2、准备数据：控制台读取System.in
    BufferedReader reader = null;

    private int formPort;
    private String toIp;
    private int toPort;

    public UdpSendClient(int formPort, String toIp, int toPort) {
        this.formPort = formPort;
        this.toIp = toIp;
        this.toPort = toPort;
    }
    @Override
    public void run() {
        try {
            // 指定自己的端口号
            socket= new DatagramSocket(formPort);
        } catch (SocketException e) {
            e.printStackTrace();
        }
        while (true){
            try {
                reader = new BufferedReader(new InputStreamReader(System.in));
                String data = reader.readLine();
                final byte[] bytes = data.getBytes();
                //new InetSocketAddress(this.toIp,this.toPort) 指定要发送的ip和端口
                final DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length,new InetSocketAddress(this.toIp,this.toPort));
                socket.send(packet);
                if(data.equals("bye")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
